from django.shortcuts import render
from django.views import generic
from django.http import HttpResponse
from django.shortcuts import redirect

from . import cart
from shop.models import Product
from . import forms
from coupons.forms import CouponApplyForm


class CartDisplay(generic.View):

    """ Отображение корзины пользователя """

    def get(self, request):

        user_cart = cart.Cart(request)
        user_cart.add_update_form()
        coupon_apply_form = CouponApplyForm()

        context = {'user_cart': user_cart,
                   'coupon_apply_form': coupon_apply_form}

        return render(request, 'cart/detail.html', context)


class AddingProduct(generic.View):

    """ Добавляем продукт в корзину пользователя """

    def post(self, request, slug):

        form = forms.AddProductForm(request.POST)

        if form.is_valid():

            cd = form.cleaned_data
            quantity, update_cart = cd['quantity'], cd['update_cart']
            print(f'updae_cart - {update_cart}')
            user_cart = cart.Cart(request)
            product = Product.objects.get(slug=slug)
            user_cart.add(product, quantity, update_cart)

            return redirect('cart:display_cart')


class RemovingProduct(generic.View):

    """ Удаление продукта из корзины """

    def get(self, request, slug):

        product = Product.objects.get(slug=slug)
        user_cart = cart.Cart(request)
        user_cart.remove(product)

        return redirect('cart:display_cart')


class ClearCart(generic.View):

    """ Очищаем корзину пользователя """

    def get(self, request):

        user_cart = cart.Cart(request)
        user_cart.clear()

        return redirect('cart:display_cart')
